package com.mulanweb.db.common;

import org.dom4j.DocumentHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.*;

/**
 * Created by Administrator on 2016/8/10.
 */
public class WxParaFormatter {

    public static String getRequestXml(SortedMap<Object, Object> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = ""+entry.getValue();
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            } else {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 将xml解析成map
     *
     * @param stringXml String 类型的xml
     * @return map 类型的 para
     */
    public static Map<String, String> xmlToMap(String stringXml) throws ParserConfigurationException, IOException, SAXException {
        Map<String, String> result = new HashMap<String, String>();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(stringXml)));

        Element root = doc.getDocumentElement();
        NodeList books = root.getChildNodes();
        if (books != null) {
            for (int i = 0; i < books.getLength(); i++) {
                Node book = books.item(i);
                String key = book.getNodeName();
                String value = null;
                Node node = book.getFirstChild();
                if (node != null) {
                    value = node.getNodeValue();
                }
                result.put(key, value != null ? value : "");
                System.out.println("节点=" + key + "\ttext=" + value);
            }
        }
        return result;
    }

    public static String mapToXml(Map<String, String> para) throws IOException {
        org.dom4j.Document d = DocumentHelper.createDocument();
        org.dom4j.Element root = d.addElement("xml");
        Set<String> keys = para.keySet();
        for (String key : keys) {
            root.addElement(key).addText(para.get(key));
        }
        StringWriter sw = new StringWriter();
        d.write(sw);
        return sw.toString();
    }

    public static String mapToXml3(Map<String, String> para) throws IOException {
        org.dom4j.Document d = DocumentHelper.createDocument();
        Set<String> keys = para.keySet();
        for (String key : keys) {
            d.addElement(key).addText(para.get(key));
        }
        StringWriter sw = new StringWriter();
        d.write(sw);
        return sw.toString();
    }

    public static String mapToXml2(Map<String, Object> para) throws IOException{
        org.dom4j.Document d = DocumentHelper.createDocument();
        org.dom4j.Element root = d.addElement("xml");
        Set<String> keys = para.keySet();
        for (String key : keys) {
            root.addElement(key).addText(para.get(key).toString());
        }
        StringWriter sw = new StringWriter();
        d.write(sw);
        return sw.toString();
    }

    public static Map<String, String> jsonToMap(String json) {
        if (json.startsWith("{") && json.endsWith("}")) {
            json = json.substring(1, json.length() - 1);
            String[] jsons = json.split(",");
            Map<String, String> result = new HashMap<String, String>();
            for (String para : jsons) {
                String[] pp = para.split(":");
                if (pp.length > 1) {
                    if (pp.length > 2) {
                        for (int i = 2; i < pp.length; i++) {
                            pp[1] = pp[1] + ":" + pp[i];
                        }
                    }
                    String key = pp[0].replace("\'", "");
                    key = key.replace("\"", "");
                    String value = pp[1].replace("\'", "");
                    value = pp[1].replace("\"", "");
                    result.put(key, value);
                }
            }
            return result;
        } else {
            return null;
        }
    }
}
